package leetcode.每日一题;

import org.junit.Test;

/**
 * @author ：zsy
 * @date ：Created 2021/6/18 10:47
 * @description：
 */
public class 删除有序链表中重复元素 {

    @Test
    public void Test() {
        Solution solution = new Solution();
        ListNode listNode = solution.deleteDuplicates(new ListNode(1,
                new ListNode(1,
                        new ListNode(1,
                                new ListNode(2,
                                        new ListNode(2,
                                                new ListNode(3,
                                                        new ListNode(4,
                                                                new ListNode(4)))))))));
        while(listNode != null) {
            System.out.println(listNode);
            listNode = listNode.next;
        }
    }



    public class Solution {
        /**
         *
         * @param head ListNode类
         * @return ListNode类
         */
        public ListNode deleteDuplicates (ListNode head) {
            // write code here

            if (head == null || head.next == null){
                return head;
            }

            ListNode node = new ListNode(-1);

            node.next = head;

            ListNode p = node;
            ListNode q = head;

            while (q != null && q.next != null){

                if (q.next.val != q.val){

                    p = q;
                    q = q.next;
                }else {

                    while (q.next != null && q.val == q.next.val){
                        q = q.next;
                    }
                    q = q.next;
                    p.next = q;
                }
            }

            return node.next;
        }

    }

    public class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    '}';
        }
    }
}

